import parseStringToTokens from "./utils/parseStringToTokens";
import nextToken from "./utils/nextToken";
import toStringTokens from "./utils/toStringTokens";

class Mustache {
    private parseStringToTokens: Function
    private NextToken: Function
    private TostringTokens: Function
    constructor() {
        this.parseStringToTokens = parseStringToTokens;
        this.NextToken = nextToken;
        this.TostringTokens = toStringTokens;
    }

    // 渲染引擎
    public render(template: string, data: object): string {
        // 将模板转化为tokens数组
        let tokens = this.parseStringToTokens(template);
        // 折叠当前tokens数组
        let nextTokens = this.NextToken(tokens);
        // 赋值渲染还原成dom元素
        let resultTemplateStr = this.TostringTokens(nextTokens, data);

        return resultTemplateStr;
    }
}

let str2 = `<div class="title">
                <div>我买了个{{thing}}，好{{mood}}啊</div>
                <h1>我是{{myName}}</h1>
                {{#show}}
                    <h1>展示{{obj.a.b.c}}</h1>
                {{/show}}
                <div>
                    {{#students}}
                        学生{{name}}的爱好是
                        <ul>
                        {{#hobbies}}
                            <li>
                                {{.}}
                            </li>
                        {{/hobbies}}
                        </ul>
                    {{/students}}
                </div>
            </div>`;

let data = {
    myName: '黄彦武',
    students: [
        {
            'name': "小明",
            'hobbies': ['游泳', '健身']
        },
        {
            'name': "小工",
            'hobbies': ['篮球', '足球']
        },
        {
            'name': "校长",
            'hobbies': ['羽毛球', '吃饭', '睡觉']
        }
    ],
    thing: "华为手机",
    mood: "开心",
    show: true,
    obj: {
        a: {
            b: {
                c:100
            }
        }
    }
}

let mustache = new Mustache();
let template = mustache.render(str2, data)
let appDom = document.getElementById("app");
appDom.innerHTML = template;
console.log(template)

